package com.ssy.lingxi.platform.manage.serviceimpl.content;

import cn.hutool.core.util.StrUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.constant.ColumnTypeEnum;
import com.ssy.lingxi.platform.manage.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.manage.entity.content.MemberColumn;
import com.ssy.lingxi.platform.manage.entity.content.QMemberColumn;
import com.ssy.lingxi.platform.manage.model.request.common.CommonIdRequest;
import com.ssy.lingxi.platform.manage.model.request.common.CommonStatusRequest;
import com.ssy.lingxi.platform.manage.model.request.content.MemberColumnPageRequest;
import com.ssy.lingxi.platform.manage.model.request.content.MemberColumnRequest;
import com.ssy.lingxi.platform.manage.model.response.HotColumnResponse;
import com.ssy.lingxi.platform.manage.repository.MemberColumnRepository;
import com.ssy.lingxi.platform.manage.repository.MemberInformationRepository;
import com.ssy.lingxi.platform.manage.service.content.IMemberColumnService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 内容能力-栏目管理
 *
 * @author wyx
 * @version 2.0.0
 * @date 2021-09-28
 */
@Service
public class MemberColumnServiceImpl implements IMemberColumnService {

    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private JPAQueryFactory jpaQueryFactory;
    @Resource
    private MemberColumnRepository memberColumnRepository;
    @Resource
    private MemberInformationRepository memberInformationRepository;


    /**
     * 栏目列表
     *
     * @param request 请求参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberColumn>> page(MemberColumnPageRequest request, UserLoginCacheDTO user) {
        //表实体
        QMemberColumn qMemberColumn = QMemberColumn.memberColumn;
        //构造查询条件
        BooleanBuilder predicates = new BooleanBuilder();

        predicates.and(qMemberColumn.memberId.eq(user.getMemberId()));
        predicates.and(qMemberColumn.memberRoleId.eq(user.getMemberRoleId()));
        if (StrUtil.isNotBlank(request.getName())) {
            predicates.and(qMemberColumn.name.like("%" + request.getName() + "%"));
        }

        JPAQuery<MemberColumn> query = jpaQueryFactory.select(qMemberColumn).from(qMemberColumn).where(predicates);

        long totalCount = query.fetchCount();

        List<MemberColumn> list = query.orderBy(qMemberColumn.id.desc())
                .offset(request.getCurrentOffset())
                .limit(request.getPageSize())
                .fetch();
        return Wrapper.success(new PageData<>(totalCount, list));
    }

    /**
     * 栏目详情
     *
     * @param request 请求参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberColumn> get(CommonIdRequest request) {
        MemberColumn memberColumn = memberColumnRepository.findById(request.getId()).orElse(null);
        if (memberColumn == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        return Wrapper.success(memberColumn);
    }

    /**
     * 新增栏目
     *
     * @param request 请求参数
     * @return 操作结果
     */
    @Override
    @Transactional
    public Wrapper<Void> add(MemberColumnRequest request, UserLoginCacheDTO user) {
        if (memberColumnRepository.existsByMemberIdAndMemberRoleIdAndSortAndType(user.getMemberId(), user.getMemberRoleId(), request.getSort(), request.getType())) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SORT_CANNOT_BE_REPEATED);
        }

        MemberColumn memberColumn = new MemberColumn();
        BeanUtils.copyProperties(request, memberColumn);
        memberColumn.setMemberId(user.getMemberId());
        memberColumn.setMemberRoleId(user.getMemberRoleId());
        memberColumnRepository.saveAndFlush(memberColumn);
        return Wrapper.success();
    }

    /**
     * 修改栏目
     *
     * @param request 请求参数
     * @return 操作结果
     */
    @Override
    @Transactional
    public Wrapper<Void> update(MemberColumnRequest request, UserLoginCacheDTO user) {
        MemberColumn existsContentColumn = memberColumnRepository.findByMemberIdAndMemberRoleIdAndSortAndType(user.getMemberId(), user.getMemberRoleId(), request.getSort(), request.getType());
        if (existsContentColumn != null && existsContentColumn.getId() - request.getId() != 0) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SORT_CANNOT_BE_REPEATED);
        }

        MemberColumn memberColumn = memberColumnRepository.findById(request.getId()).orElse(null);
        if (memberColumn == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if (memberColumn.getStatus().equals(CommonBooleanEnum.YES.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }

        BeanUtils.copyProperties(request, memberColumn);
        memberColumnRepository.saveAndFlush(memberColumn);
        return Wrapper.success();
    }

    /**
     * 停用/启用
     *
     * @param request 请求参数
     * @return 操作结果
     */
    @Override
    @Transactional
    public Wrapper<Void> updateStatus(CommonStatusRequest request, UserLoginCacheDTO user) {
        //停用栏目时, 需要先判断该栏目是否被资讯信息所关联, 如果有则不能被停用
        if (request.getEnableStatus().equals(CommonBooleanEnum.NO.getCode())) {
            if (memberInformationRepository.existsAllByColumnId(request.getId())) {
                throw new BusinessException(ResponseCode.MAN_DATA_RELATION_INFORMATION);
            }
        }

        MemberColumn memberColumn = memberColumnRepository.findById(request.getId()).orElse(null);
        if (memberColumn == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        memberColumn.setStatus(request.getEnableStatus());
        memberColumnRepository.saveAndFlush(memberColumn);
        return Wrapper.success();
    }

    /**
     * 删除栏目
     *
     * @param request 请求参数
     * @return 操作结果
     */
    @Override
    @Transactional
    public Wrapper<Void> delete(CommonIdRequest request, UserLoginCacheDTO user) {
        //删除栏目时, 需要先判断该栏目是否被资讯信息所关联, 如果有则不能被停用
        if (memberInformationRepository.existsAllByColumnId(request.getId())) {
            throw new BusinessException(ResponseCode.MAN_DATA_RELATION_INFORMATION);
        }

        MemberColumn memberColumn = memberColumnRepository.findById(request.getId()).orElse(null);
        if (memberColumn == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if (memberColumn.getStatus().equals(EnableDisableStatus.ENABLE.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        memberColumnRepository.delete(memberColumn);
        return Wrapper.success();
    }

    /**
     * 所有栏目
     *
     * @param type 栏目分类：1.市场行情；2.资讯
     * @return 查询结果
     */
    @Override
    public Wrapper<List<MemberColumn>> all(Integer type, UserLoginCacheDTO user) {
        List<MemberColumn> all;
        if (type != null) {
            all = memberColumnRepository.findAllByMemberIdAndMemberRoleIdAndStatusAndType(user.getMemberId(), user.getMemberRoleId(), CommonBooleanEnum.YES.getCode(), type, Sort.by("id"));
        } else {
            all = memberColumnRepository.findAllByMemberIdAndMemberRoleIdAndStatus(user.getMemberId(), user.getMemberRoleId(), CommonBooleanEnum.YES.getCode(), Sort.by("id"));
        }
        return Wrapper.success(all);
    }

    /**
     * 所有（市场行情）
     *
     * @return 查询结果
     */
    @Override
    public Wrapper<List<MemberColumn>> allByMarket(UserLoginCacheDTO user) {
        List<MemberColumn> all = memberColumnRepository.findAllByMemberIdAndMemberRoleIdAndStatusAndType(user.getMemberId(), user.getMemberRoleId(), CommonBooleanEnum.YES.getCode(), ColumnTypeEnum.MARKET.getCode(), Sort.by("sort"));
        return Wrapper.success(all);
    }

    /**
     * 热门栏目
     *
     * @return 查询结果
     */
    @Override
    public Wrapper<List<HotColumnResponse>> hot(UserLoginCacheDTO user) {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT mcc.id, mcc.name, ");
        sql.append(" (SELECT COUNT(mci.id) FROM man_member_information mci WHERE mci.status = 2 AND mci.column_id = mcc.id) num ");
        sql.append(" FROM man_member_column mcc WHERE mcc.status = 1 ");
        sql.append(" AND mcc.member_id = ").append(user.getMemberId());
        sql.append(" AND mcc.member_role_id = ").append(user.getMemberRoleId());
        sql.append(" ORDER BY sort ");
        List<HotColumnResponse> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(HotColumnResponse.class));
        return Wrapper.success(list.stream().filter(a -> !a.getNum().equals(0)).collect(Collectors.toList()));
    }
}
